<?php

namespace App\Admin\Forms;

use Dcat\EasyExcel\Excel;
use Dcat\Admin\Widgets\Form;
use App\Models\Coin;

class CoinImportForm extends Form
{
    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return \Dcat\Admin\Http\JsonResponse
     */
    public function handle(array $input)
    {
        // 获取上传的文件路径
        $file_path = storage_path('app/public/' . $input['import_file']);

        // 读取excel文件
        $data = Excel::import($file_path)->toArray();

        if (empty($data) || !isset($data['Sheet1']) || count($data['Sheet1']) <= 0) {
            return $this->response()->error('Excel文件无数据或格式不正确');
        }

        // 处理数据
        $success = 0;
        $error = 0;

        foreach ($data['Sheet1'] as $k => $row) {
            if ($k === 0) {
                // 跳过表头
                continue;
            }
            // 确保必要字段存在
            if (empty($row['名称']) || empty($row['类型'])) {
                $error++;
                continue;
            }

            // 获取类型值
            $type = null;
            foreach (Coin::TYPE as $key => $value) {
                if ($value === $row['类型']) {
                    $type = $key;
                    break;
                }
            }

            if ($type === null) {
                $error++;
                continue;
            }

            // 创建新硬币
            Coin::create([
                'name' => $row['名称'],
                'type' => $type,
                'address' => $row['地址'] ?? '',
                'longitude' => $row['经度'] ?? '',
                'latitude' => $row['纬度'] ?? '',
                'is_true' => $type == Coin::TYPE_JIN ? (isset($row['真假']) && $row['真假'] === '真' ? Coin::IS_TRUE_YES : Coin::IS_TRUE_NO) : Coin::IS_TRUE_YES,
            ]);

            $success++;
        }

        $message = "导入完成，成功导入 {$success} 条记录";
        if ($error > 0) {
            $message .= "，{$error} 条记录导入失败";
        }

        return $this->response()->success($message)->refresh();
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        // 禁用重置表单按钮
        $this->disableResetButton();

        // 文件上传
        $this->file('import_file', '选择Excel文件')
            ->disk('public')
            ->accept('xls,xlsx')
            ->uniqueName()
            ->autoUpload()
            ->move('/import')
            ->help('支持xls,xlsx格式，请按照模板格式填写数据');
    }
}
